package com.namuan.jp_stock.activity;

import org.json.JSONException;
import org.json.JSONObject;

import twitter4j.Twitter;
import twitter4j.TwitterException;

import com.facebook.android.AsyncFacebookRunner;
import com.facebook.android.FBaseRequestListener;
import com.facebook.android.FSessionStore;
import com.facebook.android.Facebook;
import com.namuan.jp_stock.dialog.SelectStockDialog;
import com.namuan.jp_stock.object.ShotActivity;
import com.namuan.jp_stock.util.AsyncJustplaceRunner;
import com.namuan.jp_stock.util.BaseRequestListener;
import com.namuan.jp_stock.util.Justplace;
import com.namuan.jp_stock.util.JustplaceError;
import com.namuan.jp_stock.util.ObjUtils;
import com.namuan.jp_stock.util.SessionStore;
import com.namuan.jp_stock.util.Util;
import com.namuan.jp_stock.R;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.RatingBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

/**
 * @author Administrator
 *
 */
public class AddActivity extends Activity implements OnClickListener {


	private TextView userHeaderNickname;
	
	private TextView tvStockName;
	private TextView tvStockNumber;
	private EditText editNickname;
	private EditText editComment;
	
	private ImageView navBtn1;
	private ImageView navBtn2;
	private ImageView navBtn3;
	private ImageView navBtn4;
		
	private final int STOCK_ACTIVITY = 0;
	
	private Justplace mJutplace;
	private AsyncJustplaceRunner mAsyncRunner;
	
	private Intent addFullActivityIntent;
	private Facebook mFacebook;
    private AsyncFacebookRunner mFAsyncRunner;
    private Twitter twitterApi;
	private RelativeLayout rLayoutStock;
	
	
	String str_usernickname = null;
	String str_stocknumber = null;
	String str_stockname = null;
	String str_comment = null;
	String str_activitypw = null;
	String str_recommendation = null;
	String str_trackbackcount = null;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.addactivity);

		userHeaderNickname = (TextView) findViewById(R.id.userHeaderNickname);
        ImageButton headerDoneBtn =(ImageButton)findViewById(R.id.headerDoneBtn);
        headerDoneBtn.setOnClickListener(this);
        
        rLayoutStock = (RelativeLayout)findViewById(R.id.rLayoutStock);
        tvStockName = (TextView) findViewById(R.id.tvStockName);
		tvStockNumber = (TextView) findViewById(R.id.tvStockNumber);
		editNickname = (EditText) findViewById(R.id.editNickname);
		editComment = (EditText) findViewById(R.id.editComment);
		
        navBtn1 = (ImageView)findViewById(R.id.navBtn1);
		navBtn2 = (ImageView)findViewById(R.id.navBtn2);
		navBtn3 = (ImageView)findViewById(R.id.navBtn3);
		navBtn4 = (ImageView)findViewById(R.id.navBtn4);
        
		userHeaderNickname.setOnClickListener(this);
		rLayoutStock.setOnClickListener(this);
        
        navBtn1.setOnClickListener(this);
		navBtn2.setOnClickListener(this);
		navBtn3.setOnClickListener(this);
		navBtn4.setOnClickListener(this);		
        
        mJutplace = new Justplace();
		SessionStore.restore(mJutplace, this);
		mAsyncRunner = new AsyncJustplaceRunner(mJutplace);
		mFacebook = new Facebook();
       	mFAsyncRunner = new AsyncFacebookRunner(mFacebook);
       	mJutplace.setHeader(userHeaderNickname);       	
       	if(userHeaderNickname.toString() != null) {
       		editNickname.setText(userHeaderNickname.getText().toString());
			editNickname.setEnabled(false);	
		}
       	
       	FSessionStore.restore(mFacebook, this);
       	twitterApi=mJutplace.getTwitterApi();
	}
	

    public void postOnWall(String msg,String photoUrl) {
        Log.d("Tests", "Testing graph API wall post");
                
        Bundle parameters = new Bundle();
        parameters.putString("message", msg);
        parameters.putString("description", "JustPlace Wine from Android");
        //parameters.putString("picture",Justplace.PROFILEIMG_URL + photoUrl);
        
        mFAsyncRunner.request("me/feed", parameters, "POST",new WallPostRequestListener(),null);
             
    }
    public class WallPostRequestListener extends FBaseRequestListener{
    	 public void onComplete(final String response, final Object state) {
    		 Log.d("Justplace-AddShot-WallPost", "Response: " + response.toString());
      
    	 }
    }
    
    
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.headerDoneBtn:
			// checkValue();
			str_comment = editComment.getText().toString();
			str_usernickname = editNickname.getText().toString();
			str_activitypw = "1";
			if (false) {

			} else if (false) {

			} else {
				Bundle params = new Bundle();
				params.putString("usernickname", str_usernickname);
				params.putString("stocknumber", str_stocknumber);
				params.putString("stockname", str_stockname);
				params.putString("comment", str_comment);
				params.putString("activitypw", str_activitypw);

				/**/
				mAsyncRunner.request("registeractivity.do", params, "POST",
						new AddActivityRequestListener(), null);
				/**/
			}
			break;
		case  R.id.rLayoutStock:
			Intent intentSelectStock = new Intent(getApplicationContext(), SelectStockDialog.class);
			startActivityForResult(intentSelectStock, STOCK_ACTIVITY);		
		break;
		
		case R.id.userHeaderNickname:
			Intent userHeaderIdintent = new Intent(this, MyProfileActivity.class);
		    this.startActivity(userHeaderIdintent);
		    overridePendingTransition(R.anim.fade, R.anim.hold);
			break;
		case R.id.navBtn1://main
			/**
			aa.clear();
			aa.notifyDataSetChanged();
			if(text_end_of_list != null) {
				activityListView.removeFooterView(text_end_of_list);
				text_end_of_list = null;
			}
			if(footerView.getParent() != null) {
				activityListView.removeFooterView(footerView);
			}
			Bundle params = new Bundle();
			mAsyncRunner.request("loadallactivitys.do", params, "GET", new LoadActivityRequestListener(), null);
			**/
			break;
			
		case R.id.navBtn2:// stock line
		/*
		Intent navBtn2intent = new Intent(this, StockActivity.class);
		this.startActivity(navBtn2intent);
		overridePendingTransition(R.anim.fade, R.anim.hold);*/
		//finish();
		break;
		
	case R.id.navBtn3:// friends line
		/*
		Intent navBtn3intent = new Intent(this, FriendsActivity.class);
		this.startActivity(navBtn3intent);
		overridePendingTransition(R.anim.fade, R.anim.hold);*/
		//finish();
		break;
		
	case R.id.navBtn4:// profile
		/*
		Intent navBtn4intent = new Intent(this, MyProfileActivity.class);
		this.startActivity(navBtn4intent);
		overridePendingTransition(R.anim.fade, R.anim.hold);
		*/
		//finish();
		break;
			
		}
	}

	 public class AddActivityRequestListener extends BaseRequestListener {

	        public void onComplete(final String response, final Object state) {
	        	 Log.d("Justplace-AddShot", "Response: " + response.toString());
	        	 JSONObject json;
				try {
					json = Util.parseJson(response);
					String strActivityid = json.getString("resultactivity");
					if(strActivityid != null) {
						ShotActivity shotactivity = ObjUtils.jsonToShotActivity(json.getJSONObject("activity"));
						//postOnWall(addWineCommentText.getText().toString()+"\n"+"("+winename+" @"+storename+")",json.getString("activitypic"));
						//postOnWall(json.getString("comment")+"\n"+"("+ json.getString("winename")+"@"+json.getString("storename")+")",json.getString("activitypic"));
						if(twitterApi!=null){
				        	try {
				            	twitterApi.updateStatus(editComment.getText().toString()+"\n"+"("+tvStockName.getText().toString()+" @ 주식SNS)"+" http://stock.namuan.co.kr/");
				            	Log.d("~~~~~~~~~~~~~~~~~~~~~~twitter success~~~~~~~~~~~~~~~~~~~~", "success");
				            	
				    		} catch (TwitterException e) {
				    			// TODO Auto-generated catch block
				    			Log.d("~~~~~~~~~~~~~~~~~~~~~~twitter fail~~~~~~~~~~~~~~~~~~~~", "fail");
				    			e.printStackTrace();
				    		}
				        }
						Intent mainActivityIntent = new Intent(getApplicationContext(), MainActivity.class);
						mainActivityIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
						AddActivity.this.startActivity(mainActivityIntent);
						overridePendingTransition(R.anim.fade, R.anim.hold);
						finish();
					}
					
					
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (JustplaceError e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
	        }
	    }
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		if(resultCode == RESULT_OK && data != null){
			 switch(requestCode){
			 case  STOCK_ACTIVITY:
				 str_stockname = data.getStringExtra("stockname");
				 str_stocknumber = data.getStringExtra("stocknumber");
				 tvStockName.setText(str_stockname);
				 tvStockNumber.setText(str_stocknumber);
				 break;
			 }
		}
	}
    
    

}
